package com.fs.uc.nacos;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.fs.uc.base.MyConfig;
import io.quarkus.runtime.Startup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.transaction.TransactionScoped;

/**
 * @author 崔超
 * 2021/12/11
 */
@ApplicationScoped
@Startup
class NacosRegister {
    private static final Logger LOGGER = LoggerFactory.getLogger(NacosRegister.class);

    @Inject
    MyConfig config;
    NamingService naming;

    @PostConstruct
    private void register() {
        try {
            naming = NamingFactory.createNamingService(config.nacos().serverAddress());
            naming.registerInstance(config.nacos().serviceName(), config.nacos().group(), config.nacos().instanceIp(), config.nacos().instancePort());
        } catch (NacosException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
    }

    @PreDestroy
    private void unregister() {
        try {
            naming.deregisterInstance(config.nacos().serviceName(), config.nacos().group(), config.nacos().instanceIp(), config.nacos().instancePort());
        } catch (NacosException e) {
            LOGGER.error(e.getMessage());
        }
    }

    String getInstance(String serviceName) throws NacosException {
        Instance basicInfo = naming.selectOneHealthyInstance(serviceName,config.nacos().group());
        return basicInfo.toInetAddr();
    }
}
